import 'dart:async';
import 'dart:convert';

import 'package:base_lib/common/bloc/base_bloc.dart';
import 'package:base_lib/common/index.dart';
import 'package:base_lib/index.dart';
import 'package:base_lib/router/routers.dart';
import 'package:doctor_login_lib/cache/userinfo_cache.dart';
import 'package:doctor_login_lib/login/entity/doctor_login_entity.dart';
import 'package:doctor_prescribe_lib/offline/basic_info/bloc.dart';
import 'package:doctor_prescribe_lib/repository/http.dart';
import 'package:flutter/src/widgets/framework.dart';
import '../../doctor_prescribe_component.dart';
import 'package:doctor_prescribe_lib/western_medicine/medical_search/entity/medical_search_entity.dart'
    as MedicineSearchBean;

///处方开立页
class PrescriptionPageBloc extends BaseBloc {
  /// 处方页添加的药品列表
  static List<MedicineSearchBean.Datas> rxMedicineList = [];

  StreamController<List<MedicineSearchBean.Datas>> listStream =
      StreamController.broadcast();

  StreamController<bool> loadingStatusStream = StreamController.broadcast();

  @override
  void initState() async {
    super.initState();
    doctorUser = await UserInfoCache.getInstance().get();
    basicInfoData = OfflineBasicInfoBloc.basicInfoData;
  }

  @override
  void dispose() {
    listStream?.close();
    loadingStatusStream?.close();
    rxMedicineList.clear();
  }

  BasicInfoData basicInfoData;
  DoctorUser doctorUser;

  void jump2MedicalSearch(BuildContext context) {
    Routers.navigateTo(context, DoctorPrescribeComponent.medicalSearchPage,
            parameters: Parameters()
              ..putString('orgID', doctorUser.orgID)
              ..putInt('orgTypeID', doctorUser.orgTypeID))
        .then((value) {
      if (value == true) {
        doRefresh();
      }
    });
  }

  void doRefresh() {
    listStream.add(rxMedicineList);
  }

  void doDelete(BuildContext context, MedicineSearchBean.Datas item) {
    rxMedicineList.remove(item);
    doRefresh();
  }

  void doEdit(BuildContext context, MedicineSearchBean.Datas item) {
    Routers.navigateTo(context, DoctorPrescribeComponent.medicalEditPage,
            parameters: Parameters()..putObj('item', item))
        .then((value) {
      doRefresh();
    });
  }

  void doNext(BuildContext context) async {
    if (rxMedicineList.length > 5) {
      ToastUtil.warning("药品数量最大不能超过5种！");
      return;
    } else if (rxMedicineList.isEmpty) {
      ToastUtil.warning("请添加药品！");
      return;
    }

    loadingStatusStream.add(true);
    double amount = 0.0;

    rxMedicineList.forEach((rx) {
      // FLog(rx.medicineFormID);
      amount += rx.price;
    });
    FLog(amount);

    basicInfoData.offlineRpEntity.rp.recipeAllPrice = amount;
    basicInfoData.offlineRpEntity.rpMedicines = rxMedicineList;

    var result = await PrescribeHttp.postOfflineRp(
        json.encode(basicInfoData.offlineRpEntity));
    loadingStatusStream.add(false);
    Future.delayed(Duration(milliseconds: 100));
    if (result.isSuccess) {
      Routers.navigateTo(context, DoctorPrescribeComponent.rpOrderPage,
          parameters: Parameters()..putString('rpID', result.data));
    } else {
      ToastUtil.error(result.error.msg);
    }
  }
}
